<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <!-- 搜索 -->
        <label class="el-form-item-label">物料编号</label>
        <el-input v-model.trim="query.productNo" clearable placeholder="物料编号" style="width: 185px;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
        <label class="el-form-item-label">标签号</label>
        <el-input v-model.trim="query.serialNo" clearable placeholder="标签号" style="width: 185px;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
        <label class="el-form-item-label">物料名称</label>
        <el-input v-model.trim="query.productDescription" clearable placeholder="物料名称" style="width: 185px;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
        <label class="el-form-item-label">入库时间</label>
        <el-date-picker
          v-model="query.inboundTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="filter-item"
          @change="toQuery"
        />
        <label class="el-form-item-label">生产时间</label>
        <el-date-picker
          v-model="query.creationDate"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="filter-item"
          @change="toQuery"
        />
        <label class="el-form-item-label">冻结状态</label>
        <el-select v-model="query.frozen" style="width: 185px;" class="filter-item" placeholder="请选择" @change="toQuery">
          <el-option
            v-for="item in frozenStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">冻结原因</label>
        <el-input v-model="query.remarksReason" clearable placeholder="冻结原因" style="width: 185px;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
        <label class="el-form-item-label">解冻原因</label>
        <el-input v-model="query.unfreezeReason" clearable placeholder="解冻原因" style="width: 185px;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
        <label class="el-form-item-label">物料类型</label>
        <el-select v-model="query.quality" style="width: 185px;" class="filter-item" placeholder="请选择" @change="toQuery">
          <el-option
            v-for="item in dict.material_type.map(item => {
              return {
                ...item,
                disabled: item.label.includes('RPA')
              }
            })"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
            :disabled="item.disabled === true"
          />
        </el-select>
        <span>
          <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
          <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置</el-button>
          <el-button class="filter-item" :disabled="selectItem.length === 0" type="primary" size="mini" icon="el-icon-lock" @click="freezeButton">冻结</el-button>
          <el-button class="filter-item" :disabled="selectItem.length === 0" type="success" size="mini" icon="el-icon-unlock" @click="unFreezeButton">解冻</el-button>
          <el-button class="filter-item" :disabled="selectItem.length === 0" type="danger" size="mini" icon="el-icon-box" @click="backWarehouse">退库</el-button>
          <el-button class="filter-item" type="warning" size="mini" :disabled="data.length === 0" :loading="btn.download" icon="el-icon-download" @click="downloadExcel">导出</el-button>
        </span>
      </div>
      <!-- 表单渲染 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="visible.frozen" :title="title" width="450px" @close="handlerCancel">
        <el-form ref="editForm" :model="editForm" :rules="rules" size="small" label-width="120px">
          <el-form-item v-if="mode === 'frozen'" label="冻结原因" prop="frozenReason">
            <el-input v-model="editForm.frozenReason" style="width: 250px;" />
          </el-form-item>
          <el-form-item v-else label="解冻原因" prop="unFrozenReason">
            <el-input v-model="editForm.unFrozenReason" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="操作人员" prop="remarksName">
            <el-input v-model="editForm.remarksName" style="width: 250px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="handlerCancel">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submit">确认</el-button>
        </div>
      </el-dialog>
      <!-- 表单渲染 -->
      <el-dialog :close-on-click-modal="false" :visible.sync="dialogTable" :title="title" width="50%" @close="cancelBack">
        <div style="display: flex;width: 100%;">
          <div style="flex: 1;">
            <el-table
              ref="tinyTable"
              border
              :data="selectItem"
              max-height="500px"
              size="small"
              style="width: 100%;"
            >
              <el-table-column prop="currentParentPalletCode" label="母托编码" />
              <el-table-column prop="serialNo" label="标签号" />
              <el-table-column label="操作" width="150px" align="center">
                <template slot-scope="scope">
                  <el-button type="danger" @click="delItem(scope.row, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="flex: 1;display: flex;flex-direction: column;gap: 5px;">
            <div style="display: flex;flex-direction: column;gap: 10px;" class="inner-userform">
              <el-form ref="userForm" :model="user" :rules="userRules" label-width="120px">
                <el-form-item label="退库人员工号" prop="code">
                  <el-input v-model.trim="user.code" clearable placeholder="退库人员工号" style="width: 185px;" class="filter-item" />
                </el-form-item>
                <el-form-item label="退库人员姓名" prop="name">
                  <el-input v-model.trim="user.name" clearable placeholder="退库人员姓名" style="width: 185px;" class="filter-item" />
                </el-form-item>
                <el-form-item label="优先级" prop="priority">
                  <el-select v-model="user.priority" class="filter-item" clearable placeholder="请选择" style="width: 185px;">
                    <el-option
                      v-for="item in priorityList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="退库时间" prop="moveDate">
                  <el-date-picker
                    v-model="user.moveDate"
                    type="datetime"
                    placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 185px"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="cancelBack">取消</el-button>
          <el-button type="primary" :loading="btn.confirmBack" :disabled="selectItem.length === 0" @click="createBack">创建退库单</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="loading"
        :data="data"
        size="small"
        style="width: 100%;"
        @select="handlerChange"
        @select-all="handlerAll"
        @selection-change="updateSelect"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="currentStorageType" label="储位类型">
          <template slot-scope="scope">
            {{ dict.label.storage_type[scope.row.currentStorageType] }}
          </template>
        </el-table-column>
        <el-table-column prop="productNo" label="物料编号" />
        <el-table-column prop="productDescription" label="物料描述" />
        <el-table-column prop="receiverName" label="客户" />
        <el-table-column prop="qty" label="数量" />
        <el-table-column prop="serialNo" label="标签号" />
        <el-table-column prop="creationDate" label="生产时间" />
        <el-table-column prop="inboundTime" label="入库时间" />
        <el-table-column prop="frozen" label="冻结状态">
          <template slot-scope="scope">
            {{ scope.row.frozen === 1 ? '冻结' : '未冻结' }}
          </template>
        </el-table-column>
        <el-table-column prop="remarksReason" label="冻结原因" />
        <el-table-column prop="remarksName" label="冻结人名" />
        <el-table-column prop="unfreezeReason" label="解冻原因" />
        <el-table-column prop="unfreezeName" label="解冻人名" />
        <!-- <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="点击此按钮,将冻结该物料,是否继续?"
              @confirm="freeze(scope.row)"
            >
              <el-button slot="reference" type="primary" size="mini">冻结</el-button>
            </el-popconfirm>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="点击此按钮,将冻结该物料,是否继续?"
              @confirm="unFreeze(srope.row)"
            >
              <el-button slot="reference" type="success" size="mini">解冻</el-button>
            </el-popconfirm>
          </template>
        </el-table-column> -->
      </el-table>
      <!--分页组件-->
      <el-pagination
        :page-size.sync="query.size"
        :total="total"
        :current-page.sync="query.current"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChangeHandler"
        @current-change="pageChangeHandler"
      />
    </div>
  </div>
</template>

<script>
import crudDefectiveProduct from '@/api/work/defectiveProduct'
// import { downloadFileAPI } from '@/api/work/defectiveProduct'
import { frozenAPI, unFrozenAPI, downloadFileAPI } from '@/api/work/defectiveProduct'
import { createReturnOrderAPI } from '@/api/work/returnStock'

export default {
  name: 'DefectiveProduct',
  dicts: ['storage_type', 'material_type'],
  data() {
    return {
      permission: {
        add: ['admin', 'storageLocation:add', 'otherUser'],
        edit: ['admin', 'storageLocation:edit', 'otherUser'],
        del: ['admin', 'storageLocation:del', 'otherUser']
      },
      rules: {
        frozenReason: [
          { required: true, message: '请输入冻结原因', trigger: 'blur' }
        ],
        unFrozenReason: [
          { required: true, message: '请输入解冻原因', trigger: 'blur' }
        ],
        remarksName: [
          { required: true, message: '请输入操作人员姓名', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'storageCode', display_name: '储位编码' },
        { key: 'storageType', display_name: '储位类型' }
      ],
      data: [],
      loading: false,
      query: {
        current: 1,
        size: 10
      },
      total: 0,
      visible: {
        frozen: false,
        unfrozen: false
      },
      title: '',
      mode: '',
      editForm: {
        frozenReason: '',
        unFrozenReason: '',
        remarksName: ''
      },
      dialogTable: false,
      selectItem: [],
      submitLoading: false,
      btn: {
        download: false,
        confirmBack: false
      },
      user: {
        code: '',
        name: '',
        priority: '',
        moveDate: ''
      },
      frozenStatusList: [
        {
          value: 1,
          label: '冻结'
        },
        {
          value: 0,
          label: '未冻结'
        }
      ],
      priorityList: [
        {
          value: 1,
          label: '中'
        },
        {
          value: 2,
          label: '高'
        }
      ],
      userRules: {
        code: [
          { required: true, message: '退库人员工号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '退库人员姓名不能为空', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '优先级不能为空', trigger: 'change' }
        ],
        moveDate: [
          { required: true, message: '退库时间不能为空', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    this.toQuery()
  },
  methods: {
    getTable() {
      this.loading = true
      crudDefectiveProduct.getTable(this.query).then(res => {
        this.data = res.data.content
        this.total = res.data.totalElements
        this.loading = false
        this.selectItem.forEach((item) => {
          this.$nextTick(() => {
            this.data.find(obj => {
              if (item.serialNo === obj.serialNo) {
                this.$refs.table.toggleRowSelection(obj, true)
              }
            })
          })
        })
      }).catch(err => {
        console.log(err)
        this.loading = false
      })
    },
    toQuery() {
      this.query.current = 1
      this.getTable()
    },
    resetQuery() {
      this.total = 0
      this.visible = {
        frozen: false,
        unfrozen: false
      }
      this.title = ''
      this.mode = ''
      this.editForm = {
        frozenReason: '',
        unFrozenReason: '',
        remarksName: ''
      }
      this.selectItem = []
      this.$refs.table.clearSelection()
      this.query = {
        current: 1,
        size: 10
      }
      this.submitLoading = false
      this.getTable()
    },
    // 当前页改变
    pageChangeHandler(e) {
      this.query.current = e
      this.getTable()
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      this.query.size = e
      this.query.current = 1
      this.getTable()
    },
    freezeButton() {
      this.mode = 'frozen'
      this.title = '冻结'
      this.visible.frozen = true
    },
    unFreezeButton() {
      this.mode = 'unFrozen'
      this.title = '解冻'
      this.visible.frozen = true
    },
    handlerCancel() {
      this.mode = ''
      this.title = ''
      this.editForm = {
        frozenReason: '',
        unFrozenReason: '',
        remarksName: ''
      }
      this.submitLoading = false
      this.visible.frozen = false
    },
    async submit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          if (this.mode === 'frozen') {
            const submitForm = {
              remarksName: this.editForm.remarksName,
              remarksReason: this.editForm.frozenReason,
              serialNoList: this.selectItem.map(item => item.serialNo)
            }
            const res = await frozenAPI(submitForm)
            if (res.result === 'OK') {
              this.$message.success('冻结成功')
              this.resetQuery()
            } else {
              this.handlerCancel()
              this.$message.warning(res.data)
            }
          } else {
            const submitForm = {
              unfreezeName: this.editForm.remarksName,
              unfreezeReason: this.editForm.unFrozenReason,
              serialNoList: this.selectItem.map(item => item.serialNo)
            }
            // 解冻
            const res = await unFrozenAPI(submitForm)
            if (res.result === 'OK') {
              this.$message.success('解冻成功')
              this.resetQuery()
            } else {
              this.handlerCancel()
              this.$message.warning(res.data)
            }
          }
        } else {
          return
        }
      })
    },
    // handlerSelect(selection) {
    //   console.log(selection)
    //   this.selectItem = selection.map(item => item.serialNo)
    // },
    // handlerSelectAll(selection) {
    //   console.log(selection)
    //   this.selectItem = selection.map(item => item.serialNo)
    // },
    // 单删
    handlerChange(selection, row) {
      let a = 0
      selection.forEach(v => {
        if (v.serialNo !== row.serialNo) {
          a++
        }
      })
      if ((a !== 0 && selection.length !== 0) || (a === 0 && selection.length === 0)) {
        this.selectItem.forEach((v, index) => {
          if (v.serialNo === row.serialNo) {
            this.selectItem.splice(index, 1)
          }
        })
      }
    },
    // 全选删除
    handlerAll(val) {
      if (val.length === 0) {
        const set2 = new Set(this.data.map(v => v.serialNo))
        const a = this.selectItem.map(v => v.serialNo).filter(item => !set2.has(item))
        const b = this.selectItem.filter(v => a.includes(v.serialNo))
        this.selectItem = b
      }
    },
    // 更新到表格
    updateSelect(val) {
      for (var i = 0; i < val.length; i++) {
        const n = {
          currentParentPalletCode: val[i].currentParentPalletCode,
          serialNo: val[i].serialNo
        }
        if (this.selectItem.length === 0) {
          this.selectItem.push(n)
        } else {
          let a = 0
          for (var j = 0; j < this.selectItem.length; j++) {
            if (this.selectItem[j].serialNo === val[i].serialNo) {
              a++
            }
          }
          if (a < 1) {
            this.selectItem.push(n)
          }
        }
      }
    },
    async downloadExcel() {
      try {
        this.btn.download = true
        const res = await downloadFileAPI(this.query)
        if (res && res instanceof Blob) {
          this.downloadFile(res)
        } else {
          this.message.warning('数据导出失败，返回数据不是有效的文件内容')
        }
      } finally {
        this.btn.download = false
      }
    },
    downloadFile(obj) {
      const url = window.URL.createObjectURL(new Blob([obj]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const fileName = 'XXX.xlsx'
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    },
    backWarehouse() {
      this.dialogTable = true
      this.title = '退库'
      // for (let i = 0; i < 5; i++) {
      //   this.selectItem.push(...this.selectItem)
      // }
    },
    createBack() {
      this.$refs.userForm.validate(async(valid) => {
        if (valid) {
          const submitForm = {
            applicantEmployeeNo: this.user.code,
            applicantName: this.user.name,
            returnMoveTime: this.user.moveDate,
            priority: this.user.priority,
            parentPalletCodeList: this.selectItem.map(item => item.currentParentPalletCode),
            moveWareHouseOrderType: 2
          }
          try {
            this.btn.confirmBack = true
            const res = await createReturnOrderAPI(submitForm)
            if (res.result === 'OK') {
              this.selectItem = []
              this.toQuery()
              this.$message.success('创建成功')
              this.user = {
                code: '',
                name: '',
                priority: '',
                moveDate: ''
              }
            } else {
              this.$message.warning(res.data)
            }
          } finally {
            this.$refs.userForm.resetFields()
            this.btn.confirmBack = false
            this.dialogTable = false
          }
        } else {
          return
        }
      })
    },
    cancelBack() {
      this.user = {
        code: '',
        name: '',
        priority: '',
        moveDate: ''
      }
      this.title = ''
      this.dialogTable = false
      this.$refs.userForm.resetFields()
    },
    delItem(row, index) {
      this.selectItem.splice(index, 1)
      this.$nextTick(() => {
        this.data.find(obj => {
          if (obj.serialNo === row.serialNo) {
            this.$refs.table.toggleRowSelection(obj, false)
          }
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
// .inner-userform {
//   .el-form {
//     ::v-deep el-form-item__label {
//       text-align: left !important;
//     }
//     ::v-deep .el-form-item--small {
//       margin-bottom: 0 !important;
//     }
//   }
// }
</style>
